import { Form } from 'antd'
import useMessage from '@/hooks/useMessage'
import { ProFormText } from '@ant-design/pro-components'
import { userResetPasswordUserIdApi } from '@/apis/payment'
import { BasicDrawer, BasicDrawerProps } from '@/components/BasicDrawer'

export default function UpdatePasswordDrawer({ register, onFinished }: BasicDrawerProps) {
  const [form] = Form.useForm()
  const { message } = useMessage()
  const { initialValues, onClose } = register()

  async function onDrawerFinished() {
    const userId = initialValues?.userId
    if (!userId) return message.error('请选择用户后再操作')
    const { password } = await form.validateFields()
    const { success } = await userResetPasswordUserIdApi({ userId, password })
    if (success) {
      message.success('重置密码成功')
      onClose?.()
      onFinished?.()
    }
  }

  return (
    <BasicDrawer
      width={400}
      form={form}
      title="重置密码"
      register={register}
      layout="horizontal"
      labelCol={{ span: 6 }}
      onFinish={onDrawerFinished}
    >
      <ProFormText.Password
        allowClear
        label="新密码"
        name="password"
        rules={[{ required: true, message: '新密码不能为空' }]}
      />
      <ProFormText.Password
        label="重复密码"
        name="confirmPassword"
        rules={[
          { required: true, message: '重复密码不能为空' },
          ({ getFieldValue }) => ({
            validator(_, value) {
              if (value !== getFieldValue('password')) {
                return Promise.reject('两次输入的密码不一致')
              }
              return Promise.resolve()
            }
          })
        ]}
      />
    </BasicDrawer>
  )
}
